<template>
  <div class="app-container">
    <!-- 页面标题 -->
    <div class="page-header">
      <el-breadcrumb separator="/">
        <el-breadcrumb-item :to="{ path: '/system' }">系统管理</el-breadcrumb-item>
        <el-breadcrumb-item :to="{ path: '/system/studentRank' }">我的段位</el-breadcrumb-item>
        <el-breadcrumb-item>作业减免权益兑换</el-breadcrumb-item>
      </el-breadcrumb>
    </div>

    <!-- 1. 当前经验值与段位提示 -->
    <el-card shadow="hover" style="margin-bottom: 20px;">
      <div class="exp-info">
        <span class="exp-label">当前段位：</span>
        <span class="rank-value">{{ currentRank && currentRank.rankLevel ? currentRank.rankLevel : '暂无' }} {{ currentRank && currentRank.rankSubLevel ? currentRank.rankSubLevel : '' }}</span>
        <span class="exp-label" style="margin-left: 20px;">当前可用经验值：</span>
        <span class="exp-value">{{ currentExp || 0 }}</span>
        <el-tooltip content="经验值可通过完成任务、考核获得" placement="top">
          <i class="el-icon-question"></i>
        </el-tooltip>
      </div>
    </el-card>

    <!-- 2. 权益列表（可兑换） -->
    <el-card shadow="hover" style="margin-bottom: 20px;">
      <div slot="header" class="card-header">
        <span class="card-title">可兑换作业减免权益</span>
      </div>
      <el-row :gutter="20" style="margin-top: 10px;">
        <el-col :span="8" v-for="(benefit, index) in benefitList" :key="benefit.id">
          <el-card class="benefit-card" :border="true">
            <div class="benefit-name">{{ benefit.benefitName }}</div>
            <div class="benefit-desc">{{ benefit.benefitDesc }}</div>
            <div class="benefit-cost">
              <span class="cost-label">所需经验：</span>
              <span class="cost-value">{{ benefit.needExp }}</span>
            </div>
            <el-button 
              type="primary" 
              size="mini" 
              style="margin-top: 15px;"
              @click="handleExchange(benefit.id, benefit.needExp)"
              :disabled="!canExchange(benefit.needExp)"
            >
              {{ currentExp < benefit.needExp ? '需降级兑换' : '立即兑换' }}
            </el-button>
          </el-card>
        </el-col>
      </el-row>
    </el-card>

    <!-- 3. 兑换历史记录 -->
    <el-card shadow="hover" class="history-card">
      <div slot="header" class="card-header">
        <span class="card-title">我的兑换历史</span>
      </div>
      <el-table 
        :data="exchangeHistoryList" 
        border 
        stripe
        fit
        size="mini"
        v-if="exchangeHistoryList.length > 0"
        class="history-table"
      >
        <el-table-column prop="benefitName" label="权益名称" width="200"></el-table-column>
        <el-table-column prop="costExp" label="消耗经验值" width="150"></el-table-column>
        <el-table-column prop="exchangeTime" label="兑换时间" width="200">
          <template #default="scope">
            {{ parseTime(scope.row.exchangeTime, '{yyyy}-{mm}-{dd} {hh}:{ii}:{ss}') }}
          </template>
        </el-table-column>
        <el-table-column prop="status" label="状态" width="120">
          <template #default="scope">
            <el-tag :type="scope.row.status === 1 ? 'info' : scope.row.status === 2 ? 'success' : 'danger'">
              {{ scope.row.status === 1 ? '已兑换' : scope.row.status === 2 ? '已使用' : '已失效' }}
            </el-tag>
          </template>
        </el-table-column>
      </el-table>
      <el-empty description="暂无兑换记录" v-else style="padding: 40px 0;"></el-empty>
    </el-card>
  </div>
</template>

<script>
import studentBenefitApi from '@/api/system/studentBenefit'
import studentRankApi from '@/api/system/studentRank'
import { parseTime } from '@/utils/index'
import { mapGetters } from 'vuex'

export default {
  name: 'StudentBenefitExchange',
  data() {
    return {
      benefitList: [],          // 可兑换权益列表
      exchangeHistoryList: [], // 兑换历史记录
      currentExp: 0,           // 当前可用经验值
      currentRank: null        // 当前段位信息
    }
  },
  computed: {
    ...mapGetters(['id']) // 从Vuex获取用户ID
  },
  created() {
    this.loadBenefitList()
    this.loadExchangeHistory()
    this.loadCurrentExp()
    this.loadCurrentRank()
  },
  methods: {
    // 判断是否可以兑换（即使经验不足也允许降级兑换）
    canExchange(needExp) {
      return true // 后端控制降级逻辑，前端始终允许点击
    },

    /**
     * 加载可兑换权益列表
     */
    loadBenefitList() {
      studentBenefitApi.getBenefitList()
        .then(response => {
          this.benefitList = response.data
        })
        .catch(error => {
          this.$message.error('获取权益列表失败：' + (error.msg || '网络错误'))
        })
    },

    /**
     * 加载兑换历史
     */
    loadExchangeHistory() {
      studentBenefitApi.getExchangeHistory()
        .then(response => {
          this.exchangeHistoryList = response.data
        })
        .catch(error => {
          this.$message.error('获取兑换历史失败：' + (error.msg || '网络错误'))
        })
    },

    /**
     * 加载当前经验值
     */
    loadCurrentExp() {
      studentBenefitApi.getCurrentExp()
        .then(response => {
          this.currentExp = response.data
        })
        .catch(error => {
          this.$message.error('获取经验值失败：' + (error.msg || '网络错误'))
        })
    },

    /**
     * 加载当前段位信息
     */
    loadCurrentRank() {
      studentRankApi.getCurrentRank(this.id)
        .then(response => {
          this.currentRank = response.data || {} // 避免模板渲染报错
        })
        .catch(error => {
          this.$message.error('获取段位信息失败：' + (error.msg || '网络错误'))
          this.currentRank = {}
        })
    },

    /**
     * 处理兑换操作（区分正常/降级兑换）
     */
    handleExchange(benefitId, needExp) {
      if (this.currentExp >= needExp) {
        this.confirmNormalExchange(benefitId)
      } else {
        this.confirmDowngradeExchange(benefitId, needExp)
      }
    },

    /**
     * 正常兑换确认（经验充足）
     */
    confirmNormalExchange(benefitId) {
      this.$confirm('确认兑换该权益吗？', '兑换确认', {
        confirmButtonText: '确认兑换',
        cancelButtonText: '取消',
        type: 'info'
      }).then(() => {
        this.doExchange(benefitId, false) // 不需要降级
      }).catch(() => {
        this.$message.info('已取消兑换')
      })
    },

    /**
     * 降级兑换确认（经验不足）
     */
    confirmDowngradeExchange(benefitId, needExp) {
      const deficit = needExp - this.currentExp // 经验差额
      this.$confirm(`当前经验值不足（差额：${deficit}）！\n确认通过降级兑换该权益吗？`, '经验不足 - 降级兑换', {
        confirmButtonText: '确认降级兑换',
        cancelButtonText: '取消',
        type: 'error', // 红色警告样式
        distinguishCancelAndClose: true
      }).then(() => {
        this.doExchange(benefitId, true) // 需要降级
      }).catch(action => {
        if (action === 'cancel') {
          this.$message.info('已取消兑换')
        }
      })
    },

    /**
     * 执行兑换请求（核心修复：正确传递参数）
     */
    doExchange(benefitId, needDowngrade = false) {
      // 调用API时传递单个benefitId和needDowngrade，匹配API定义
      studentBenefitApi.exchangeBenefit(benefitId, needDowngrade)
        .then(response => {
          this.$message.success(response.msg)
          // 兑换后刷新所有数据
          this.loadCurrentExp()
          this.loadExchangeHistory()
          this.loadCurrentRank()
          this.$emit('refreshExp') // 通知段位页面刷新
        }).catch(error => {
          this.$message.error(error.msg || '兑换失败')
        })
    }
  }
}
</script>

<style scoped>
.page-header {
  margin-bottom: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.card-title {
  font-size: 16px;
  font-weight: 700;
  color: #1f2d3d;
}

.exp-info {
  font-size: 14px;
  color: #1f2d3d;
  display: flex;
  align-items: center;
  gap: 10px;
  padding: 10px 0;
}

.exp-value {
  font-size: 16px;
  font-weight: 700;
  color: #409eff;
}

.rank-value {
  font-size: 16px;
  font-weight: 700;
  color: #f56c6c;
}

.benefit-card {
  height: 100%;
  display: flex;
  flex-direction: column;
  align-items: center;
  padding: 20px 10px;
  text-align: center;
  transition: all 0.3s ease;
}

.benefit-card:hover {
  transform: translateY(-5px);
  box-shadow: 0 4px 12px rgba(0,0,0,0.1);
}

.benefit-name {
  font-size: 16px;
  font-weight: 700;
  color: #1f2d3d;
  margin-bottom: 10px;
}

.benefit-desc {
  font-size: 12px;
  color: #666;
  margin-bottom: 15px;
  flex: 1;
}

.benefit-cost {
  font-size: 14px;
  color: #1f2d3d;
  margin-bottom: 10px;
}

.cost-value {
  color: #f56c6c;
  font-weight: 700;
}

/* 兑换历史表格样式 */
.history-card {
  width: 100%; 
}
.history-table {
  width: 100% !important; 
}
.el-table--fit {
  border-right: 1px solid #ebeef5;
}

.el-table tr {
  transition: all 0.3s ease;
}

.el-table tr:hover {
  background-color: #f9fafc;
}

.el-tag {
  padding: 4px 8px;
  border-radius: 4px;
}
</style>